package com.wetool.wechat.controller;

import com.wetool.wechat.feign.WechatOpenPlatformFeignClient;
import com.wetool.wechat.model.open.WechatAccessTokenResponse;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by zhangjie on 8/7/17.
 */
@Controller
public class WechatPaymentController {
    private final static Logger logger = LoggerFactory.getLogger(WechatPaymentController.class);

    @Value("${wetool.js-pay-url.dev}")
    private String jsPayUrlDev;    // 支付下单URL（开发环境）

	@Value("${wetool.js-pay-url.st}")
	private String jsPayUrlSt;	// 支付下单URL（测试环境）
	
    @Value("${wetool.js-pay-url.pro}")
    private String jsPayUrlPro;    // 支付下单URL（生产环境）

	@Value("${wetool.js-pay-ok-url.dev}")
	private String jsPayOkUrlDev;	// 支付下单成功URL（开发环境）
	
	@Value("${wetool.js-pay-ok-url.st}")
	private String jsPayOkUrlSt;	// 支付下单成功URL（测试环境）
	
	@Value("${wetool.js-pay-ok-url.pro}")
	private String jsPayOkUrlPro;	// 支付下单成功URL（生产环境）
	
    @Value("${wechat.official-account.appId}")
    private String officialAppId;
    
    @Value("${wechat.official-account.appSecret}")
    private String officialAppSecret;

    @Autowired
    private WechatOpenPlatformFeignClient wechatOpenPlatformFeignClient;

    /**
     * 微信扫码支付回调
     *
     * @param payOrderId
     * @param active
     * @param code
     * @param status
     * @param model
     * @return
     */
    @ApiOperation(value = "微信支付回调地址")
    @RequestMapping(value = {"/callback"}, method = {RequestMethod.GET})
    public String paymentCallback(String chargeKey, String merchantId, String merchantName, String mchId, String payTypeCode, String active, String code, String status, Model model) {
        logger.info("进入接口 > 微信回调. 参数：chargeKey={}, merchantId={}, merchantName={}, mchId={},payTypeCode={},active={},code={}, status={}", chargeKey, merchantId, merchantName, mchId, payTypeCode, active, code, status);
        try {
            String grantType = "authorization_code";
            WechatAccessTokenResponse response = this.wechatOpenPlatformFeignClient.accessToken(officialAppId, officialAppSecret, code, grantType);
            logger.info("response==null：{},response={}", response == null, response);
            if (response != null && !StringUtils.isEmpty(response.getOpenId())) {
                model.addAttribute("userId", response.getOpenId());
        		model.addAttribute("chargeKey", chargeKey);	// 收款二维码
        		model.addAttribute("merchantId", merchantId);	// 商家ID
        		model.addAttribute("merchantName", merchantName);	// 商家名称
        		model.addAttribute("mchId", mchId);	// 商户号（威富通生成）
        		model.addAttribute("payTypeCode", payTypeCode);	// 支付类型编号
				if("pro".equals(active)) {
					model.addAttribute("payUrl", jsPayUrlPro);
					model.addAttribute("payOkUrl", jsPayOkUrlPro);
				} else if("dev".equals(active)) {
					model.addAttribute("payUrl", jsPayUrlDev);
					model.addAttribute("payOkUrl", jsPayOkUrlDev);
				} else if("st".equals(active)) {
					model.addAttribute("payUrl", jsPayUrlSt);
					model.addAttribute("payOkUrl", jsPayOkUrlSt);
				} else {
                    logger.info("未知的配置环境，无法进行跳转，active=" + active);
                }
            } else {
                logger.info("openId获取失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("接口结束 < 微信回调.");
        return "pay/wechat-confirm";
    }
}